import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoadingController } from '@ionic/angular';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { Sentence } from 'src/app/model/sentence';
import { DeleteSentence, GetSentences } from '../store/actions/app.action';
import { AppState } from '../store/state/app.state';

@Component({
  selector: 'app-management',
  templateUrl: 'management.page.html',
  styleUrls: ['management.page.scss'],
})
export class ManagementPage implements OnInit {
  @Select(AppState.getSentences)
  public sentences: Observable<Sentence[]>;

  @Select(AppState.getCurrentChapterNo)
  public currentChapterNo: Observable<number>;

  constructor(public loadingCtrl: LoadingController, private router: Router, private store: Store) {}
  public async ngOnInit() {
    const loading = await this.loadingCtrl.create({
      message: '数据加载...',
    });
    await loading.present();

    this.store.dispatch(new GetSentences()).subscribe({
      error: async () => await loading.dismiss(),
      complete: async () => await loading.dismiss(),
    });
  }

  public async modify(sentence: Sentence) {
    await this.router.navigate(['/tabs/management/modification'], {
      state: sentence,
    });
  }
  public async remove(sentence: Sentence) {
    const loading = await this.loadingCtrl.create({
      message: '数据处理...',
    });
    await loading.present();

    this.store.dispatch(new DeleteSentence(sentence.id)).subscribe({
      error: async () => await loading.dismiss(),
      complete: async () => await loading.dismiss(),
    });
  }

  public async gotoNextChapter() {
    const loading = await this.loadingCtrl.create({
      message: '数据处理...',
    });
    await loading.present();

    this.store.dispatch(new GetSentences(1)).subscribe({
      error: async () => await loading.dismiss(),
      complete: async () => await loading.dismiss(),
    });
  }
  public async gotoPreviousChapter() {
    const loading = await this.loadingCtrl.create({
      message: '数据处理...',
    });
    await loading.present();
    this.store.dispatch(new GetSentences(-1)).subscribe({
      error: async () => await loading.dismiss(),
      complete: async () => await loading.dismiss(),
    });
  }
}
